package com.project.picxg.controller;

import com.project.picxg.util.DownloaderFile;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;

@Controller
public class Downloader {

    @RequestMapping("/Test")
    @ResponseBody
    public String Test(){
        return "成功";
    }

    @RequestMapping("/dwon1")
    @ResponseBody
    public void Down(HttpServletRequest request, HttpServletResponse response) throws Exception {
        long l = System.currentTimeMillis();
        String fileName = request.getParameter("path");
        String path = "D:\\report\\fc204581-ea70-47ee-bee8-b0ab75c64f97\\" + fileName;
            File f = new File(path);
            // 文件是否存在
            if (f.exists()) {
                DownloaderFile.SetInputOrOutputStream(f,response);
                response.reset(); // 清空缓冲区中数据，包括状态码和header信息
                // 设置响应方式,以附件形式响应给客户端
                response.setHeader("Content-Disposition",
                        "attachment;filename=" + java.net.URLEncoder.encode(fileName, "utf-8"));
                DownloaderFile.uploadReport(f);
            }
        long l1 = System.currentTimeMillis();

        System.out.println("本次传输共计用时" + (l1-l));
    }


    @RequestMapping("/down2")
    @ResponseBody
    public ResponseEntity<FileSystemResource> down(HttpServletRequest request){
        String fileName = request.getParameter("path");
        String path = "D:\\report\\fc204581-ea70-47ee-bee8-b0ab75c64f97\\" + fileName;
        File file = new File(path);
            if (file == null) {
                return null;
            }
            HttpHeaders headers = new HttpHeaders();
            headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
            headers.add("Content-Disposition", "attachment; filename=" + file.getName());
            headers.add("Pragma", "no-cache");
            headers.add("Expires", "0");
            headers.add("Last-Modified", new Date().toString());
            headers.add("ETag", String.valueOf(System.currentTimeMillis()));
            return ResponseEntity
                    .ok()
                    .headers(headers)
                    .contentLength(file.length())
                    .contentType(MediaType.parseMediaType("application/octet-stream"))
                    .body(new FileSystemResource(file));

    }
}
